package pl.edu.pw.ee.buildcity.scheduler.listeners;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import pl.edu.pw.ee.buildcity.domain.FireJobEvent;
import pl.edu.pw.ee.buildcity.scheduler.api.BuildCityScheduler;

/**
 * @author Mateusz
 * @since 2010-02-27
 */
public class FireJobListener implements ApplicationListener {

	private static final Logger log = Logger.getLogger(FireJobListener.class);

	private BuildCityScheduler buildCityScheduler;

	public FireJobListener(BuildCityScheduler buildCityScheduler) {
		if (buildCityScheduler == null) {
			throw new IllegalArgumentException("buildCityScheduler cannot be null!");
		}
		this.buildCityScheduler = buildCityScheduler;
	}

	/**
	 * Fired by spring when an {@link org.springframework.context.ApplicationEvent} was published by publisher.
	 * In this context, it checks whether event is type of {@link pl.edu.pw.ee.buildcity.domain.FireJobEvent} and if so,
	 * gets jobs name from this event and tries to run it. Otherwise, if published event is of other type, ignores it.
	 *
	 * @param event should be {@link pl.edu.pw.ee.buildcity.domain.FireJobEvent}, otherwise no action is being performed.
	 */
	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (!(event instanceof FireJobEvent)) {
			log.warn("Unknown (and so, ignored) event type: " + event);
			return;
		}
		fireJob(event);
	}

	private void fireJob(ApplicationEvent event) {
		String jobToFireName = getJobName(event);
		buildCityScheduler.fireNow(jobToFireName);
	}

	private String getJobName(ApplicationEvent event) {
		String jobName = ((FireJobEvent) event).getJobName();
		log.info("Received FireJobEvent with jobName: '" + jobName + "'");
		return jobName;
	}
}
